package ac.neec.mio.ui.graph;

import java.util.List;

import org.afree.chart.AFreeChart;
import org.afree.chart.axis.NumberAxis;
import org.afree.chart.plot.XYPlot;
import org.afree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.afree.data.xy.XYSeries;
import org.afree.data.xy.XYSeriesCollection;
import org.afree.graphics.PaintType;
import org.afree.graphics.SolidColor;
import org.afree.graphics.geom.Font;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.AttributeSet;

public class HeartRateGraph extends DemoView {

	private static final String DOMAIN_AXIS_NAME = "time";
	private static final String RANGE_AXIS_NAME = "heart";
	private static final int GRAPH_HEIGHT = 1000;
	private static final int GRAPH_WIGTH = 1100;
	private static final PaintType GRAPH_BACK_COLOR = new SolidColor(Color.WHITE);
	private static final PaintType LABEL_COLOR = new SolidColor(Color.rgb(100, 100, 100));
	private static final Font LABEL_FONT = new Font(Typeface.SANS_SERIF, Typeface.BOLD, 30);
	private static final int FONT_SIZE = 30;

	private XYSeriesCollection data;
	private NumberAxis domainAxis;
	private NumberAxis rangeAxis;
	private XYPlot plot;
	private AFreeChart aFreeChart;
	private List<Integer> graphData;

	public HeartRateGraph(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void createChart(List<Integer> graphData) {

		this.graphData = graphData;
		// X軸の定義
		domainAxis = new NumberAxis(DOMAIN_AXIS_NAME);
		// Y軸の定義
		rangeAxis = new NumberAxis(RANGE_AXIS_NAME);
		// 折れ線の定義
		XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();

		setGraphSize();
		setGraphLabel();
		setFontSize();
		setGraphData();

		plot = new XYPlot(data, domainAxis, rangeAxis, renderer);
		aFreeChart = new AFreeChart(plot);
		//背景色の設定
		aFreeChart.setBackgroundPaintType(GRAPH_BACK_COLOR);
		setChart(aFreeChart);
	}

	private void setGraphSize() {
		setMaximumDrawWidth(GRAPH_WIGTH);
		setMaximumDrawHeight(GRAPH_HEIGHT);
	}

	private void setGraphLabel() {
		domainAxis.setLabelFont(LABEL_FONT);
		rangeAxis.setLabelFont(LABEL_FONT);
		domainAxis.setLabelPaintType(LABEL_COLOR);
		rangeAxis.setLabelPaintType(LABEL_COLOR);
		domainAxis.setTickLabelFont(LABEL_FONT);
	}

	private void setFontSize() {
		Font tickFont = new Font(Typeface.MONOSPACE, Typeface.NORMAL, FONT_SIZE);
		domainAxis.setTickLabelFont(tickFont);
		rangeAxis.setTickLabelFont(tickFont);
	}

	private void setGraphData(){
		XYSeries xy = new XYSeries("");
		int i = 0;
		try {
			for (int value : graphData) {
				xy.add(i + 1, value);
				i++;
			}
		} catch (NullPointerException e) {
		}
		data = new XYSeriesCollection(xy);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
	}

}
